package com.briup.cms.web.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.briup.cms.exception.CustomerException;
import com.briup.cms.utils.JwtUtil;
import com.briup.cms.utils.MessageStatus;
import com.briup.cms.utils.SecurityUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author wood
 * @date 2021/4/9 - 23:53
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) {
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }

        // 从 http 请求头中取出 Authorization 字段的值，也是jwt的token值
        String token = httpServletRequest.getHeader("Authorization");

        if (token == null) {
            throw new CustomerException(MessageStatus.USER_TOKEN_NOT_EXIST);
        }

        // 验证 token
        try {
            JwtUtil.checkSign(token);
        } catch (JWTVerificationException e) {
            throw new CustomerException(MessageStatus.USER_TOKEN_INVALID);
        }

        saveInfo(httpServletRequest,JwtUtil.getInfo(token));

        // 验证通过后，这里测试取出JWT中存放的数据
        // 获取 token 中的 userId
//        String userId = JwtUtil.getUserId(token);
//        System.out.println("id:" + userId);

        // 获取 token 中的 其他数据
//        Map<String, Object> info = JwtUtil.getInfo(token);
//        info.forEach((k,v)->System.out.println(k+":"+v));


        return true;
    }

    private void saveInfo(HttpServletRequest httpServletRequest,Map<String, Object> map){
        String method = httpServletRequest.getMethod();
        String requestURI = httpServletRequest.getRequestURI();

        String username = (String) map.get("username");
        String realname = (String) map.get("realname");

        SecurityUtils.setmethod(method);
        SecurityUtils.setRequestURI(requestURI);
        SecurityUtils.setUsername(username);
        SecurityUtils.setRealname(realname);

    }

}
